#!/usr/bin/env bash
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2024 Huawei Technologies Co., Ltd. All rights reserved.

# TODO: 依赖 jq yum-utils
# TODO: 使用不同软件包，拆分功能函数

# TODO: 暂时手动指定
PROJECT_DIR=/root/x2epkg
source $PROJECT_DIR/rpm_convert.sh
EPKG_HASH_EXEC=/root/epkg-hash-x86

# TODO: 本地repo仓库可传参, 后缀名（传参？自动识别？）
SOURCE_PACKAGE_NAME=
SOURCE_PACKAGE_DIR=
SOURCE_REPO_NAME=openEuler2409-local
SOURCE_PACKAGE_SUFFIX=rpm

X2EPKG_CACHE_DIR=$HOME/.cache/x2epkg
X2EPKG_SOURCE_DIR=$X2EPKG_CACHE_DIR/source
X2EPKG_DEST_DIR=$X2EPKG_CACHE_DIR/convert
X2EPKG_EPKG_DIR=$X2EPKG_CACHE_DIR/epkg

declare -A pkg_hash_dict

while [[ $# -gt 0 ]]; do
    case $1 in
        --help|-h)
            echo "Usage: x2epkg [OPTION]... [FILE]..."
            echo "  --src PATH       Convert all packages in the specified path."
            echo "  --src_repo REPO  Use the specified repo file for conversion."
            echo "  --dest PATH      Place converted packages in the specified path."
            echo "  FILE             Convert a single package."
            exit 0
            ;;
        --src)
            SOURCE_PACKAGE_DIR="$2"
            shift 2
            ;;
        --src_repo)
            SOURCE_REPO_NAME="$2"
            shift 2
            ;;
        --dest)
            X2EPKG_DEST_DIR="$2"
            mkdir -p $X2EPKG_DEST_DIR
            shift 2
            ;;
        -*|--*)
            echo "Error: Unknown option $1"
            exit 1
            ;;
        *)  
            SOURCE_PACKAGE_NAME="$1"
            shift
            ;;
    esac
done

# Single pkg convert
if [ -n "$SOURCE_PACKAGE_NAME" ]; then
    rpm_convert "$SOURCE_PACKAGE_NAME"
    exit 0
fi

# Batch pkg convert
for pkg in "$SOURCE_PACKAGE_DIR"/*."$SOURCE_PACKAGE_SUFFIX"; do
    rpm_convert "$pkg"
    echo "$pkg convert success"
done
